import ConfigParser
import sys
from twisted.internet import reactor
from twisted.protocols import sip
from twisted.internet.protocol import ServerFactory

from ESL import ESLconnection


class SipProxy(sip.Proxy):
    """The actual Proxy SBC"""

    def __init__(self):
        """this code just runs"""
        sip.Proxy.__init__(self, host=listenip, port=5060)

    def handle_request(self, message, addr):
        """Proxy all requests, we don;t currently care wha they are"""

        print
        message.toString()
        print
        dir(message)
        if message.method == 'ACK':
            return
        # Now, get the lest loaded server
        server = LoadBalancer.getserver(fslist)

        response = self.responseFromRequest(302, message)
        response.addHeader("Contact", "sip:127.0.0.1:5060")
        response.creationFinished()
        self.deliverResponse(response)
        print
        response
        print
        addr


"""
class sipfactory(ServerFactory):

        protocol=SipProxy
"""


class LoadBalancer:
    """The FreeSWITCH Load Balancer.
    Currently uses Current_Calls/Max_Calls=%load"""

    def getserver(fslist):
        """gets the best server to redirect the nect action to"""
        try:
            for server in server_list(len(fslist)):
                con = ESLconnection(server, esl_port, esl_pass)

            # are we connected?
            if con.connected():
                # run command
                e = con.api('show calls count')
                print
                e.getBody()

            else:
                print
                "Not Connected"
                sys.exit(2)

        except:
            print
            "error connecting to server" + server


class setup:
    """setup class that gets everything initialized"""
    config = ConfigParser.RawConfigParser()
    config.read('/etc/pysbc.cfg')
    myip = config.get('pysbc_config', 'listen_ip')
    server_list = config.get('freeswitch_config', 'server_list')
    server_list = server_list.split(",")
    esl_pass = config.get('freeswitch_config', 'esl_pass')
    esl_port = config.get('freeswitch_config', 'esl_port')


sconfig = setup()
listenip = sconfig.myip
fslist = sconfig.server_list
reactor.listenUDP(5060, SipProxy(), listenip)
reactor.run()